﻿#ifndef _EASY_SELECT_CLIENT_H_
#define _EASY_SELECT_CLIENT_H_

#include "EasyTcpClient.hpp"

class EasySelectClient : public EasyTcpClient
{
public:
	virtual ~EasySelectClient()
	{
		Close();
	}

	// 发送数据
	// 处理网络消息
	virtual bool OnRun(int microseconds) override
	{
		if (!IsRun())
		{
			return false;
		}
		SOCKET sock = _pClient->sockfd();
		FD_ZERO(&_fRead);
		FD_SET(sock, &_fRead);
		FD_ZERO(&_fWrite);
		struct timeval ti = { 0, microseconds };
		int ret = 0;
		// 如果客户端缓冲区里有数据可以发送给服务端，就添加可写检测
		if (_pClient->needWrite())
		{
			FD_SET(sock, &_fWrite);
			ret = select(sock + 1, &_fRead, &_fWrite, nullptr, &ti);
		}
		else
		{
			ret = select(sock + 1, &_fRead, nullptr, nullptr, &ti);
		}

		if (ret < 0)
		{
			CELLLog_Error("<sock=%d> OnRun select error exit on line %d", (int)sock, __LINE__);
			Close();
			return false;
		}

		if (FD_ISSET(sock, &_fRead))
		{
			if (RecvData() == SOCKET_ERROR)
			{
				CELLLog_Error("<sock=%d> RecvData select error exit on line %d", (int)sock, __LINE__);
				Close();
				return false;
			}
		}

		if (FD_ISSET(sock, &_fWrite))
		{
			if (_pClient->SendDataReal() == SOCKET_ERROR)
			{
				CELLLog_Error("<sock=%d> SendDataReal select error exit on line %d", (int)sock, __LINE__);
				Close();
				return false;
			}
		}
		return true;
	}
private:
	fd_set _fRead;
	fd_set _fWrite;
};

#endif
